<template>
    <view class="chat-detail-page">
      <!-- 顶部导航栏（仅居中显示昵称与状态） -->
    <view class="header-bar">
        <view class="header-center only-center">
          <view class="header-info">
            <text class="header-name">{{ chatUser?.nickname || '未知用户' }}</text>
            <text class="header-status" :class="{ online: chatUser?.isOnline }">
              {{ chatUser?.isOnline ? '在线' : '离线' }}
            </text>
          </view>
      </view>
    </view>

      <!-- 聊天消息区域 -->
      <scroll-view 
        class="chat-messages" 
        scroll-y="true" 
        :scroll-top="scrollTop"
        :scroll-into-view="scrollIntoView"
        :scroll-with-animation="true"
        @scrolltoupper="loadMoreMessages"
        @scroll="onScroll"
      >
        <!-- 加载更多历史消息按钮 -->
        <view v-if="hasMoreMessages && !loadingMore" class="load-more-container">
          <button class="load-more-btn" @click="loadMoreMessages">加载更多历史消息</button>
        </view>
        
        <view v-if="loadingMore" class="loading-more">
        <span class="spinner"></span>
          <text>加载历史消息中...</text>
      </view>
      
        <view v-if="loading && messages.length === 0" class="loading-spinner">
          <span class="spinner"></span>
          <text>加载中...</text>
      </view>
      
        <view v-else class="messages-container">
          
          <template v-for="(message, index) in messages" :key="message.id">
            <!-- 时间标注 -->
            <view v-if="shouldShowTimeLabel(message, index)" class="time-label">
              <text class="time-text">{{ formatTimeLabel(message.createdAt) }}</text>
        </view>

            <!-- 对方消息 -->
            <view 
              v-if="Number(message.senderId) !== Number(currentUserId)"
              :id="index === messages.length - 1 ? `last-message-${messages.length}` : ''"
              class="message-item message-other"
              @click="debugMessageStyle(message)"
            >
              <view class="message-avatar" @click="goToUserProfile(chatUser?.uid)">
                <image :src="getAvatarUrl(chatUser?.avatarUrl)" class="avatar" @error="handleMessageAvatarError" />
              </view>
              <view class="message-content">
                <view class="message-bubble">
                  <text class="message-text">{{ message.content }}</text>
                  <view class="message-meta">
                    <text class="message-time">{{ formatTime(message.createdAt) }}</text>
                  </view>
                </view>
              </view>
          </view>
          
            <!-- 自己的消息 -->
            <view 
              v-else
              :id="index === messages.length - 1 ? `last-message-${messages.length}` : ''"
              class="message-item message-self"
              @click="debugMessageStyle(message)"
            >
              <view class="message-avatar" @click="goToUserProfile(currentUser?.uid)">
                <image :src="getAvatarUrl(currentUser?.avatarUrl)" class="avatar" @error="handleCurrentUserAvatarError" />
              </view>
              <view class="message-content">
                <view class="message-bubble bubble-self">
                  <text class="message-text">{{ message.content }}</text>
                  <view class="message-meta">
                    <text class="message-time">{{ formatTime(message.createdAt) }}</text>
                    <text class="message-status">
                      {{ message.isTemp ? '发送中...' : (message.status === 'sent' ? '已发送' : '已发送') }}
                    </text>
                </view>
              </view>
            </view>
          </view>
          </template>
        </view>
      </scroll-view>
  
      <!-- 滚动到底部按钮 -->
      <view v-if="unreadNewCount > 0" class="scroll-to-bottom-btn" @click="onClickNewMessageButton">
        <text class="scroll-btn-icon">↓</text>
        <text class="scroll-btn-text">{{ unreadNewCount > 99 ? '99+' : unreadNewCount }}</text>
      </view>
  
      <!-- 输入区域 -->
      <view class="input-section">
        <view class="input-container">
          <input 
            v-model="inputMessage" 
            type="text" 
            placeholder="输入消息..." 
            class="message-input"
            @confirm="sendMessage"
            :disabled="!isConnected"
          />
          <button 
            class="send-btn" 
            @click="sendMessage"
            :disabled="!inputMessage.trim() || !isConnected"
          >
            发送
          </button>
        </view>
      </view>
  
      <!-- 更多选项弹窗 -->
      <view v-if="showMoreOptions" class="modal-mask" @click.self="showMoreOptions = false">
        <view class="modal-content">
          <view class="modal-header">
            <text class="modal-title">更多选项</text>
            <button class="modal-close" @click="showMoreOptions = false">×</button>
          </view>
          <view class="modal-body">
            <button class="option-btn" @click="clearChat">清空聊天记录</button>
            <button class="option-btn" @click="blockUser">拉黑用户</button>
          </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { NETWORK_CONFIG } from '@/config/network.js'
  import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { onShow, onLoad } from '@dcloudio/uni-app'
import { useUserStore } from '@/store/user'
import { getAvatarUrl } from '@/utils/imageUtils.js'

const userStore = useUserStore()
  
  // 路由参数
  const chatUserId = ref('')
  const chatUserName = ref('')

// 页面参数获取（使用onLoad，更可靠）
onLoad(async (options) => {
  console.log('🔍 onLoad 获取到的参数:', options)
  
  chatUserId.value = Number(options.userId) || 0
  chatUserName.value = options.name || ''
  
  console.log('🔍 处理后的 chatUserId:', chatUserId.value)
  console.log('🔍 处理后的 chatUserName:', chatUserName.value)
  
  // 在onLoad中立即初始化聊天功能
  if (chatUserId.value) {
    console.log('🔍 onLoad中初始化聊天功能')
    await initializeChat()
  }
})

// 数据
const loading = ref(false)
  const messages = ref([])
  const inputMessage = ref('')
const isConnected = ref(false)
  const showMoreOptions = ref(false)
  const scrollTop = ref(0)
  const scrollIntoView = ref('')
  const chatUser = ref(null)
  const currentUser = ref(null)
  const currentUserId = ref('')
  const suppressUnread = ref(false) // 首次进入或首屏滚动安定前，抑制未读提示累加
  const isUserScrolling = ref(false) // 用户是否正在手动滚动
  const shouldAutoScroll = ref(true) // 是否应该自动滚动（位于底部附近）
  const unreadNewCount = ref(0) // 未读新消息计数（非底部时累加）
  const isInitialLoad = ref(true) // 是否是首次加载
  
  // 分页相关
  const currentPage = ref(0)
  const pageSize = ref(10)
  const hasMoreMessages = ref(true)
  const loadingMore = ref(false)

// WebSocket连接
let ws = null

// 聊天初始化函数
const initializeChat = async () => {
  console.log('🔍 开始初始化聊天功能')
  
  // 确保userStore.profile已加载
  if (!userStore.profile) {
    console.log('userStore.profile为空，尝试获取用户信息...')
    try {
      await userStore.fetchUserProfile()
      console.log('获取用户信息成功:', userStore.profile)
    } catch (error) {
      console.error('获取用户信息失败:', error)
    }
  }
  
  currentUserId.value = Number(userStore.profile?.uid) || 0
  currentUser.value = userStore.profile
  
  console.log('初始化调试:')
  console.log('userStore.profile:', userStore.profile)
  console.log('userStore.profile?.uid:', userStore.profile?.uid, '类型:', typeof userStore.profile?.uid)
  console.log('currentUserId.value:', currentUserId.value, '类型:', typeof currentUserId.value)
  console.log('Number(userStore.profile?.uid):', Number(userStore.profile?.uid))
  console.log('Number(currentUserId.value):', Number(currentUserId.value))
  
  // 检查userStore是否为空
  if (!userStore.profile) {
    console.error('❌ userStore.profile 为空！')
  }
  if (!userStore.profile?.uid) {
    console.error('❌ userStore.profile.uid 为空！')
  }
  
  console.log('页面初始化调试信息:')
  console.log('路由参数 userId:', chatUserId.value, '类型:', typeof chatUserId.value)
  console.log('路由参数 name:', chatUserName.value)
  console.log('处理后的 chatUserId:', chatUserId.value, '类型:', typeof chatUserId.value)
  console.log('当前用户ID:', currentUserId.value, '类型:', typeof currentUserId.value)
  
  // 检查参数是否正确
  if (chatUserId.value === currentUserId.value) {
    console.error('错误：聊天用户ID不能等于当前用户ID！')
    console.error('chatUserId:', chatUserId.value, 'currentUserId:', currentUserId.value)
  }
  
  if (chatUserId.value) {
    // 首屏进入抑制未读按钮、防止乱滚
    suppressUnread.value = true
    
    // 先加载用户信息，再加载消息
    await loadChatUser()
    await loadMessages(0, false) // 首次加载最新10条消息
    
    connectWebSocket()
    // 自动标记该聊天的所有消息为已读
    await markChatAsRead()
    // 进入会话时默认跟随底部并清空未读提示按钮
    shouldAutoScroll.value = true
    unreadNewCount.value = 0
    console.log('📱 初始化完成，已清零未读计数:', unreadNewCount.value)
    // 等待首屏滚动稳定后再允许未读累加
    setTimeout(() => { suppressUnread.value = false }, 400)
  }
}

// 初始化
  onMounted(async () => {
    // 不重置滚动位置，避免页面跳动
    // scrollIntoView.value = ''
    // scrollTop.value = 0
    
    // 如果onLoad没有执行（比如直接访问页面），则在这里初始化
    if (!chatUserId.value || chatUserId.value === 0) {
      console.log('🔍 onMounted 中检测到参数未设置，尝试获取参数')
      const pages = getCurrentPages()
      const currentPage = pages[pages.length - 1]
      const options = currentPage?.options || {}
      
      chatUserId.value = Number(options.userId) || 0
      chatUserName.value = options.name || ''
      console.log('🔍 onMounted 备用参数获取 - chatUserId:', chatUserId.value, 'chatUserName:', chatUserName.value)
      
      // 如果获取到了参数，则初始化聊天功能
      if (chatUserId.value) {
        console.log('🔍 onMounted中初始化聊天功能')
        await initializeChat()
      }
    }

// 监听全局WebSocket消息
  uni.$on('chatMessage', handleChatMessage)
    uni.$on('messageSent', handleMessageSent)
    uni.$on('websocketError', handleWebSocketError)
    
    // 监听页面显示：不主动滚动，避免与初次加载、watch 重复导致抖动
    onShow(() => {
      console.log('页面显示')
    })
  })
  
  // 页面隐藏/卸载时清理状态，防止下次进入复用旧状态
onUnmounted(() => {
    unreadNewCount.value = 0
    shouldAutoScroll.value = true
    suppressUnread.value = false
    scrollIntoView.value = ''
    scrollTop.value = 0
  })
  
  // 监听消息列表变化
  watch(messages, (newMessages, oldMessages) => {
    const oldLen = oldMessages?.length || 0
    const newLen = newMessages.length
    console.log('消息列表变化:', { oldLen, newLen })
    if (newLen === 0) return
    
    // 初次加载
    if (oldLen === 0 && newLen > 0) {
      // 初次加载时，滚动到最下面（最新消息）
      shouldAutoScroll.value = true
      unreadNewCount.value = 0
      suppressUnread.value = true
      isInitialLoad.value = false // 标记首次加载完成
      console.log('📱 初次加载消息，滚动到最下面（最新消息）')
      // 滚动到最下面
      setTimeout(() => scrollToBottom(true, true), 50)
      setTimeout(() => { scrollToBottom(true, true); suppressUnread.value = false }, 250)
      return
    }
    
    // 新增消息（只有在非首次加载时才处理）
    if (newLen > oldLen && !isInitialLoad.value) {
      console.log('🔍 watch(messages) 检测到新消息:', {
        shouldAutoScroll: shouldAutoScroll.value,
        suppressUnread: suppressUnread.value,
        newLen: newLen,
        oldLen: oldLen,
        isInitialLoad: isInitialLoad.value
      })
      
      if (shouldAutoScroll.value || suppressUnread.value) {
        // 在底部：自动跟随
        console.log('✅ watch(messages) 触发自动滚动')
        setTimeout(() => scrollToBottom(true, true), 50)
        // 注意：这里不清空未读计数，让 handleChatMessage 中的逻辑来处理
        // 因为我们需要区分是自己发的消息还是对方发的消息
      } else {
        // 不在底部：累加未读，显示按钮
        console.log('❌ watch(messages) 不在底部，累加未读')
        unreadNewCount.value = Math.min(unreadNewCount.value + (newLen - oldLen), 999)
      }
    }
  }, { deep: true })
  
  onUnmounted(() => {
    // 清理事件监听器
    uni.$off('chatMessage', handleChatMessage)
    uni.$off('messageSent', handleMessageSent)
    uni.$off('websocketError', handleWebSocketError)
  })
  
  // 加载聊天用户信息
  const loadChatUser = async () => {
  try {
    const token = uni.getStorageSync('accessToken')
      console.log('加载聊天用户信息，chatUserId:', chatUserId.value)
      console.log('路由传递的用户名:', chatUserName.value)
      
      // 先使用路由传递的用户名作为临时显示
      if (chatUserName.value) {
        chatUser.value = {
          uid: chatUserId.value,
          nickname: decodeURIComponent(chatUserName.value),
          isOnline: false
        }
        console.log('使用路由参数设置用户信息:', chatUser.value)
      }
      
      // 使用现有的 /info 接口获取聊天对象信息
    console.log('🔍 加载用户信息请求 - chatUserId:', chatUserId.value)
    const response = await uni.request({
        url: `${NETWORK_CONFIG.API_BASE_URL}/user/info`,
        method: 'POST',
      header: {
          'Access-Token': `Bearer ${token}`,
          'Authorization': `Bearer ${token}`
        },
        data: {
          uid: chatUserId.value.toString()
        }
      })
  
      console.log('聊天用户信息响应:', response.data)
      
      if (response.data && response.data.uid) {
        chatUser.value = response.data
        console.log('聊天用户信息加载成功:', chatUser.value)
      } else {
        console.error('获取聊天用户信息失败:', response.data)
        // 如果API失败，至少保持路由传递的用户名
        if (!chatUser.value && chatUserName.value) {
          chatUser.value = {
            uid: chatUserId.value,
            nickname: decodeURIComponent(chatUserName.value),
            isOnline: false
          }
          console.log('API失败，使用路由参数作为备选:', chatUser.value)
        }
    }
  } catch (error) {
      console.error('加载聊天用户信息失败:', error)
      // 如果API失败，至少保持路由传递的用户名
      if (!chatUser.value && chatUserName.value) {
        chatUser.value = {
          uid: chatUserId.value,
          nickname: decodeURIComponent(chatUserName.value),
          isOnline: false
        }
        console.log('API异常，使用路由参数作为备选:', chatUser.value)
      }
    }
  }
  
  // 加载聊天消息（分页）
  const loadMessages = async (page = 0, isLoadMore = false) => {
    if (isLoadMore) {
      loadingMore.value = true
    } else {
      loading.value = true
    }
    
  try {
    const token = uni.getStorageSync('accessToken')
    const requestUrl = `${NETWORK_CONFIG.API_BASE_URL}/simple-chat/messages?otherUserId=${chatUserId.value}&page=${page}&size=${pageSize.value}`
    console.log('🔍 加载消息请求URL:', requestUrl)
    console.log('🔍 请求参数 - chatUserId:', chatUserId.value, 'page:', page, 'size:', pageSize.value)
    
    const response = await uni.request({
        url: requestUrl,
      method: 'GET',
      header: {
          'Access-Token': `Bearer ${token}`,
          'Authorization': `Bearer ${token}`
        }
      })
  
      if (response.statusCode === 200 && response.data && (response.data.code === 200 || response.data.success === true)) {
        const messageList = response.data.data || []
        console.log(`加载第${page}页消息，数量:`, messageList.length)
        console.log('消息时间范围:', messageList.map(msg => ({
          id: msg.id,
          time: msg.createdAt || msg.createTime,
          content: msg.content
        })))
        
        // 确保 senderId 是数字类型
        const processedMessages = messageList.map(msg => ({
          ...msg,
          senderId: Number(msg.senderId),
          receiverId: Number(msg.receiverId)
        }))
        
        if (isLoadMore) {
          // 加载更多时，将历史消息插入到前面
          // 由于后端按DESC排序，新加载的消息是更早的，需要反转后放在前面
          const reversedMessages = processedMessages.reverse()
          messages.value = [...reversedMessages, ...messages.value]
          console.log('加载更多历史消息，总数量:', messages.value.length)
          console.log('合并后的消息顺序:', messages.value.map(msg => ({
            id: msg.id,
            time: msg.createdAt || msg.createTime,
            content: msg.content
          })))
    } else {
          // 首次加载时，反转消息顺序（后端按DESC返回，需要反转成ASC显示）
          messages.value = processedMessages.reverse()
          console.log('首次加载消息，数量:', messages.value.length)
          console.log('首次加载消息顺序:', messages.value.map(msg => ({
            id: msg.id,
            time: msg.createdAt || msg.createTime,
            content: msg.content
          })))
        }
        
        // 确保消息按时间排序（最新的在下面，聊天界面标准）
        messages.value.sort((a, b) => {
          const timeA = new Date(a.createdAt || a.createTime).getTime()
          const timeB = new Date(b.createdAt || b.createTime).getTime()
          return timeA - timeB // 升序排序，最新的在下面
        })
        
        console.log('排序后的消息顺序:', messages.value.map(msg => ({
          id: msg.id,
          time: msg.createdAt || msg.createTime,
          content: msg.content
        })))
        
        // 检查是否还有更多消息
        hasMoreMessages.value = messageList.length === pageSize.value
        
        // 如果不是加载更多，滚动到最下面（最新消息）
        if (!isLoadMore) {
          console.log('📱 首次加载消息完成，滚动到最下面（最新消息）')
          scrollToBottom()
          setTimeout(() => {
            scrollToBottom()
          }, 200)
        }
      } else if (response.statusCode === 400) {
        // 参数错误等，视为没有更多数据，避免界面报错
        hasMoreMessages.value = false
        console.warn('加载消息返回400，已视为无更多数据: ', response.data)
    }
  } catch (error) {
      console.error('加载消息失败:', error)
    } finally {
      loading.value = false
      loadingMore.value = false
    }
  }
  
  // 连接WebSocket（使用全局连接）
  const connectWebSocket = () => {
    console.log('🔍 使用全局WebSocket连接，无需创建新连接')
    console.log('🔍 当前用户ID:', currentUserId.value)
    console.log('🔍 聊天用户ID:', chatUserId.value)
    isConnected.value = true
  }
  
  // 标记该聊天的所有消息为已读
  const markChatAsRead = async () => {
    try {
    const token = uni.getStorageSync('accessToken')
      console.log('📖 标记聊天为已读，聊天用户ID:', chatUserId.value)
      
      const response = await uni.request({
      url: `${NETWORK_CONFIG.API_BASE_URL}/simple-chat/mark-read?otherUserId=${chatUserId.value}`,
      method: 'POST',
      header: { 'Access-Token': `Bearer ${token}` }
    })
    
      console.log('📖 API响应:', response.data)
      
      if (response.data && response.data.code === 200) {
        console.log('✅ 聊天已标记为已读')
        
        // 发送事件通知聊天列表页面更新
        uni.$emit('chat-marked-read', { otherUserId: chatUserId.value })
        
        // 重新计算并更新tabBar红点（延迟调用以确保数据已更新）
        setTimeout(async () => {
          try {
            const unreadResponse = await uni.request({
              url: `${NETWORK_CONFIG.API_BASE_URL}/simple-chat/real-unread-counts`,
              method: 'GET',
              header: { 'Access-Token': `Bearer ${token}` }
            })
            
            if (unreadResponse.data && unreadResponse.data.code === 200) {
              const unreadCounts = unreadResponse.data.data || {}
              const totalUnread = Object.values(unreadCounts).reduce((sum, count) => sum + count, 0)
              
              if (totalUnread > 0) {
                uni.setTabBarBadge({
                  index: 1,
                  text: totalUnread > 99 ? '99+' : totalUnread.toString()
                })
              } else {
                uni.removeTabBarBadge({ index: 1 })
              }
            }
          } catch (err) {
            console.error('更新tabBar红点失败:', err)
          }
        }, 300)
      } else {
        console.error('❌ 标记聊天为已读失败:', response.data)
      }
  } catch (error) {
      console.error('❌ 标记聊天为已读失败:', error)
    }
  }
  
  // 处理聊天消息
  const handleChatMessage = (data) => {
    console.log('🔍 detail.vue 收到聊天消息:', data)
    
    if (data.message) {
      const message = {
        ...data.message,
        senderId: Number(data.message.senderId),
        receiverId: Number(data.message.receiverId)
      }
      
      console.log('🔍 处理聊天消息:', message)
      console.log('🔍 当前用户ID:', currentUserId.value)
      console.log('🔍 聊天用户ID:', chatUserId.value)
      console.log('🔍 消息发送者ID:', message.senderId)
      console.log('🔍 消息接收者ID:', message.receiverId)
      
      // 检查消息是否属于当前聊天对象
      const isRelevantMessage = (
        (message.senderId === Number(chatUserId.value) && message.receiverId === Number(currentUserId.value)) ||
        (message.senderId === Number(currentUserId.value) && message.receiverId === Number(chatUserId.value))
      )
      
      console.log('🔍 消息过滤调试:')
      console.log('🔍 消息发送者ID:', message.senderId, '类型:', typeof message.senderId)
      console.log('🔍 消息接收者ID:', message.receiverId, '类型:', typeof message.receiverId)
      console.log('🔍 当前用户ID:', currentUserId.value, '类型:', typeof currentUserId.value)
      console.log('🔍 聊天用户ID:', chatUserId.value, '类型:', typeof chatUserId.value)
      console.log('🔍 条件1 (对方发给我):', message.senderId === Number(chatUserId.value) && message.receiverId === Number(currentUserId.value))
      console.log('🔍 条件2 (我发给对方):', message.senderId === Number(currentUserId.value) && message.receiverId === Number(chatUserId.value))
      console.log('🔍 消息是否相关:', isRelevantMessage)
      
      if (!isRelevantMessage) {
        console.log('🔍 消息不属于当前聊天对象，跳过处理')
        return
      }
      
      // 检查是否是对方发给我的消息（需要显示未读红点）
      const isFromOtherUser = message.senderId === Number(chatUserId.value) && message.receiverId === Number(currentUserId.value)
      console.log('🔍 是否来自对方用户:', isFromOtherUser)
      
      // 检查是否已存在相同消息（避免重复）
      const existingMessage = messages.value.find(msg => 
        msg.id === message.id || 
        (msg.isTemp && msg.content === message.content && msg.senderId === message.senderId)
      )
      
      if (!existingMessage) {
        console.log('🔍 添加新消息到列表')
        messages.value.push(message)
        
        // 重新排序消息，确保最新的在下面
        messages.value.sort((a, b) => {
          const timeA = new Date(a.createdAt || a.createTime).getTime()
          const timeB = new Date(b.createdAt || b.createTime).getTime()
          return timeA - timeB // 升序排序，最新的在下面
        })
        
        // 自动滚动到底部或累加未读
        console.log('🔍 处理新消息滚动逻辑:', {
          shouldAutoScroll: shouldAutoScroll.value,
          isFromOtherUser: isFromOtherUser,
          isUserScrolling: isUserScrolling.value
        })
        
        if (shouldAutoScroll.value) {
          console.log('✅ 对方发送消息，应该自动滚动')
          scrollToBottom()
          setTimeout(() => {
            scrollToBottom()
          }, 100)
          // 如果是对方发来的消息，即使自动滚动也要累加未读（用于聊天列表显示）
          if (isFromOtherUser) {
            unreadNewCount.value = Math.min(unreadNewCount.value + 1, 999)
            console.log('🔍 对方发来消息，累加未读计数:', unreadNewCount.value)
          }
        } else {
          // 对方发送消息时，如果不在底部，不滚动，只累加未读计数
          console.log('❌ 对方发送消息，不在底部，不滚动，累加未读计数')
          unreadNewCount.value = Math.min(unreadNewCount.value + 1, 999)
          console.log('🔍 对方发来消息，累加未读计数:', unreadNewCount.value)
        }
        // 通知聊天列表页面更新
        uni.$emit('newMessage', message)
      } else if (existingMessage.isTemp) {
        console.log('🔍 替换临时消息为真实消息')
        console.log('🔍 临时消息:', existingMessage)
        console.log('🔍 真实消息:', message)
        
        // 替换临时消息为真实消息
        const index = messages.value.findIndex(msg => msg === existingMessage)
        if (index !== -1) {
          messages.value[index] = message
          console.log('🔍 临时消息已替换，索引:', index)
        }
        
        // 重新排序消息，确保最新的在下面
        messages.value.sort((a, b) => {
          const timeA = new Date(a.createdAt || a.createTime).getTime()
          const timeB = new Date(b.createdAt || b.createTime).getTime()
          return timeA - timeB // 升序排序，最新的在下面
        })
        
        // 自动滚动到底部或累加未读
        if (shouldAutoScroll.value) {
          scrollToBottom()
          setTimeout(() => {
            scrollToBottom()
          }, 100)
          // 如果是对方发来的消息，即使自动滚动也要累加未读（用于聊天列表显示）
          if (isFromOtherUser) {
            unreadNewCount.value = Math.min(unreadNewCount.value + 1, 999)
            console.log('🔍 对方发来消息（替换临时消息），累加未读计数:', unreadNewCount.value)
          }
        } else {
          unreadNewCount.value = Math.min(unreadNewCount.value + 1, 999)
          console.log('🔍 不在底部（替换临时消息），累加未读计数:', unreadNewCount.value)
        }
      } else {
        console.log('🔍 消息已存在，跳过')
      }
    }
  }
  
  // 处理消息发送确认
  const handleMessageSent = (data) => {
    console.log('🔍 收到消息发送确认:', data)
    console.log('🔍 当前消息列表:', messages.value.map(msg => ({
      id: msg.id,
      content: msg.content,
      isTemp: msg.isTemp,
      senderId: msg.senderId
    })))
    
    if (data.message) {
      const message = {
        ...data.message,
        senderId: Number(data.message.senderId),
        receiverId: Number(data.message.receiverId)
      }
      
      console.log('🔍 处理发送确认消息:', message)
      
      // 查找对应的临时消息并替换
      const tempMessage = messages.value.find(msg => 
        msg.isTemp && 
        msg.content === message.content && 
        msg.senderId === message.senderId
      )
      
      console.log('🔍 查找临时消息结果:', tempMessage)
      
      if (tempMessage) {
        console.log('🔍 找到临时消息，准备替换:', tempMessage)
        const index = messages.value.findIndex(msg => msg === tempMessage)
        if (index !== -1) {
          messages.value[index] = message
          console.log('🔍 临时消息已替换为真实消息')
          
          // 重新排序
          messages.value.sort((a, b) => {
            const timeA = new Date(a.createdAt || a.createTime).getTime()
            const timeB = new Date(b.createdAt || b.createTime).getTime()
            return timeA - timeB
          })
        }
      } else {
        console.log('🔍 未找到匹配的临时消息')
        console.log('🔍 尝试更宽松的匹配条件...')
        
        // 尝试更宽松的匹配：只匹配内容和发送者
        const looseMatch = messages.value.find(msg => 
          msg.isTemp && 
          msg.content === message.content
        )
        
        if (looseMatch) {
          console.log('🔍 找到宽松匹配的临时消息:', looseMatch)
          const index = messages.value.findIndex(msg => msg === looseMatch)
          if (index !== -1) {
            messages.value[index] = message
            console.log('🔍 临时消息已替换为真实消息（宽松匹配）')
            
            // 重新排序
            messages.value.sort((a, b) => {
              const timeA = new Date(a.createdAt || a.createTime).getTime()
              const timeB = new Date(b.createdAt || b.createTime).getTime()
              return timeA - timeB
            })
          }
        } else {
          console.log('🔍 宽松匹配也未找到临时消息')
        }
      }
    } else {
      console.log('🔍 发送确认数据中没有message字段')
    }
  }
  
  // 处理WebSocket错误
  const handleWebSocketError = (data) => {
    console.log('收到WebSocket错误:', data)
    uni.showToast({
      title: data.message || '消息发送失败',
      icon: 'none'
    })
  }
  
  // 发送消息
  const sendMessage = async () => {
    if (!inputMessage.value.trim()) return
  
    const messageContent = inputMessage.value.trim()
    inputMessage.value = ''
  
    // 使用全局WebSocket发送消息
    try {
      console.log('发送消息调试信息:')
      console.log('当前用户ID:', currentUserId.value, '类型:', typeof currentUserId.value)
      console.log('聊天用户ID:', chatUserId.value, '类型:', typeof chatUserId.value)
      console.log('消息内容:', messageContent)
      
      const message = {
        type: 'chat',
        roomId: Number(chatUserId.value), // 确保是数字类型
        content: messageContent,
        messageType: 'text',
        timestamp: Date.now()
      }
      
      // 通过全局WebSocket发送消息
      uni.$emit('sendWebSocketMessage', message)
        
        // 立即添加到消息列表（乐观更新）
        const tempMessage = {
          id: Date.now(),
          senderId: Number(currentUserId.value), // 确保是数字类型
          content: messageContent,
          messageType: 'text',
          createdAt: new Date().toISOString(),
          isTemp: true // 标记为临时消息
        }
        
        console.log('添加临时消息:', tempMessage)
        messages.value.push(tempMessage)
        
        // 重新排序消息，确保最新的在下面
        messages.value.sort((a, b) => {
          const timeA = new Date(a.createdAt || a.createTime).getTime()
          const timeB = new Date(b.createdAt || b.createTime).getTime()
          return timeA - timeB // 升序排序，最新的在下面
        })
        
        // 自动滚动到底部（自己发的消息不累加未读计数）
        if (shouldAutoScroll.value) {
          console.log('✅ 自己发送消息，应该自动滚动')
          scrollToBottom()
          setTimeout(() => {
            scrollToBottom()
          }, 100)
        } else {
          // 自己发的消息不累加未读计数，但也要滚动（保持一致性）
          console.log('✅ 自己发送消息，强制滚动到底部')
          scrollToBottom()
        }
        
        // 备用方案：5秒后自动清理临时消息（防止永远卡在发送中）
        setTimeout(() => {
          const stillTempMessage = messages.value.find(msg => 
            msg.id === tempMessage.id && msg.isTemp
          )
          if (stillTempMessage) {
            console.log('🔍 临时消息超时，自动清理:', stillTempMessage)
            stillTempMessage.isTemp = false
            stillTempMessage.status = 'sent' // 标记为已发送
          }
        }, 5000)
        
        // 移除延迟刷新，避免不必要的重连
        // WebSocket会实时推送消息，不需要手动刷新
        
    } catch (error) {
      console.error('发送消息失败:', error)
      // 失败时回退到HTTP API
      sendMessageViaHTTP(messageContent)
    }
  }
  
  // HTTP API发送消息（备用方案）
  const sendMessageViaHTTP = async (messageContent) => {
    try {
      const token = uni.getStorageSync('accessToken')
      const response = await uni.request({
        url: `${NETWORK_CONFIG.API_BASE_URL}/simple-chat/messages`,
        method: 'POST',
        header: {
          'Access-Token': `Bearer ${token}`,
          'Authorization': `Bearer ${token}`
        },
        data: {
          receiverId: Number(chatUserId.value),
          content: messageContent,
          messageType: 'text'
        }
      })
  
      if (response.data && response.data.code === 200) {
        // 消息发送成功，通过WebSocket接收
        console.log('消息发送成功')
      } else {
    uni.showToast({
          title: '发送失败',
          icon: 'none'
    })
      }
  } catch (error) {
      console.error('发送消息失败:', error)
    uni.showToast({
        title: '发送失败',
      icon: 'none'
    })
  }
}

  // 加载更多消息
  const loadMoreMessages = () => {
    if (loadingMore.value || !hasMoreMessages.value) {
      return
    }
    
    console.log('📚 加载更多历史消息')
    
    // 记录当前滚动位置和消息数量，用于加载后保持位置
    const currentScrollTop = scrollTop.value
    const currentMessageCount = messages.value.length
    
    currentPage.value++
    loadMessages(currentPage.value, true)
    
    // 加载完成后，保持用户当前的滚动位置
    // 由于新消息插入到前面，需要调整滚动位置
    nextTick(() => {
      const newMessageCount = messages.value.length
      const addedMessages = newMessageCount - currentMessageCount
      
      console.log('📚 历史消息加载完成:', {
        currentScrollTop: currentScrollTop,
        currentMessageCount: currentMessageCount,
        newMessageCount: newMessageCount,
        addedMessages: addedMessages
      })
      
      // 计算新的滚动位置，保持用户看到的内容不变
      if (addedMessages > 0) {
        // 使用更精确的高度估算
        // 每条消息大约100px高度（包括间距）
        const estimatedMessageHeight = 100
        const newScrollTop = currentScrollTop + (addedMessages * estimatedMessageHeight)
        
        // 使用setTimeout确保DOM完全更新后再调整滚动位置
        setTimeout(() => {
          scrollTop.value = newScrollTop
          console.log('📍 保持滚动位置，新位置:', newScrollTop)
        }, 100)
      }
    })
  }
  
  // 滚动事件处理
  const onScroll = (e) => {
    console.log('用户滚动事件:', e.detail)
    isUserScrolling.value = true
    
    // 检测用户是否滚动到底部附近
    const { scrollTop: currentScrollTop, scrollHeight, scrollViewHeight } = e.detail
    const distanceFromBottom = scrollHeight - currentScrollTop - scrollViewHeight
    const isNearBottom = distanceFromBottom < 100 // 增加阈值，更容易检测到底部
    
    console.log('滚动检测:', {
      scrollTop: currentScrollTop,
      scrollHeight: scrollHeight,
      scrollViewHeight: scrollViewHeight,
      distanceFromBottom: distanceFromBottom,
      isNearBottom: isNearBottom
    })
    
    if (isNearBottom) {
      shouldAutoScroll.value = true
      // 回到底部后清零未读
      if (unreadNewCount.value > 0) {
        unreadNewCount.value = 0
        // 通知列表页同步清零红点
        uni.$emit('chat-consumed-unread', { otherUserId: chatUserId.value })
      }
      console.log('✅ 用户滚动到底部附近，启用自动滚动')
    } else {
      shouldAutoScroll.value = false
      console.log('❌ 用户滚动到上方，禁用自动滚动')
    }
    
    // 延迟重置用户滚动状态
    clearTimeout(onScroll._t)
    onScroll._t = setTimeout(() => { isUserScrolling.value = false }, 300)
  }
  
  // 滚动到底部
  const scrollToBottom = (smooth = true, force = false) => {
    // 如果用户正在手动滚动且不在底部，则不自动滚动（除非强制）
    if (!force && isUserScrolling.value && !shouldAutoScroll.value) {
      console.log('❌ 用户正在手动滚动，跳过自动滚动')
      return
    }
    
    console.log('✅ 开始滚动到底部，强制:', force, '平滑滚动:', smooth)
    
    // 先清空一次以确保相同 id 也能触发滚动
    scrollIntoView.value = ''
    
    // 使用nextTick确保DOM更新完成
    nextTick(() => {
      if (messages.value.length === 0) {
        console.log('❌ 没有消息，跳过滚动')
        return
      }
      
      // 方法1: 使用scroll-into-view滚动到最后一条消息（使用动态 id 防止被重用）
      const lastId = `last-message-${messages.value.length}`
      scrollIntoView.value = lastId
      console.log('📍 滚动到最后一条消息', lastId)
      
      // 方法2: 使用scroll-top确保滚动到底部
      setTimeout(() => {
        // 设置一个很大的值确保滚动到底部
        scrollTop.value = scrollTop.value + 1 // 触发 scroll-view 重新计算
        console.log('📍 使用scroll-top滚动到底部')
      }, 50)
      
      // 方法3: 再次确保滚动到底部
      setTimeout(() => {
        scrollTop.value = scrollTop.value + 1
        // 重置一次 scrollIntoView，避免后续相同 id 不再生效
        scrollIntoView.value = ''
        console.log('✅ 最终滚动完成')
      }, 220)
    })
  }
  
  // 点击新消息按钮
  const onClickNewMessageButton = () => {
    unreadNewCount.value = 0
    shouldAutoScroll.value = true
    // 强制滚动到底部
    scrollToBottom(true, true)
  }
  
  // 删除refreshPage方法，改用loadMessages

// 格式化时间
  const formatTime = (timestamp) => {
    const date = new Date(timestamp)
  const now = new Date()
  const diff = now - date
  
    if (diff < 60000) { // 1分钟内
      return '刚刚'
    } else if (diff < 3600000) { // 1小时内
      return Math.floor(diff / 60000) + '分钟前'
    } else if (diff < 86400000) { // 24小时内
      return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
    } else {
      return date.toLocaleDateString('zh-CN')
    }
  }
  
  // 格式化时间标注（显示完整时间）
  const formatTimeLabel = (timestamp) => {
    const date = new Date(timestamp)
    const now = new Date()
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
    const messageDate = new Date(date.getFullYear(), date.getMonth(), date.getDate())
    
    // 如果是今天
    if (messageDate.getTime() === today.getTime()) {
      const hours = date.getHours()
      const minutes = date.getMinutes()
      return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`
    }
    
    // 如果是昨天
    const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000)
    if (messageDate.getTime() === yesterday.getTime()) {
      const hours = date.getHours()
      const minutes = date.getMinutes()
      return `昨天 ${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`
    }
    
    // 如果是本周
    const weekAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000)
    if (messageDate.getTime() > weekAgo.getTime()) {
      const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
      const weekday = weekdays[date.getDay()]
      const hours = date.getHours()
      const minutes = date.getMinutes()
      return `${weekday} ${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`
    }
    
    // 更早的日期
    const hours = date.getHours()
    const minutes = date.getMinutes()
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    }) + ` ${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`
  }
  
  // 判断是否应该显示时间标注
  const shouldShowTimeLabel = (message, index) => {
    // 第一条消息总是显示时间
    if (index === 0) {
      return true
    }
    
    // 获取当前消息和前一条消息的时间
    const currentTime = new Date(message.createdAt || message.createTime)
    const previousMessage = messages.value[index - 1]
    const previousTime = new Date(previousMessage.createdAt || previousMessage.createTime)
    
    // 计算时间差（毫秒）
    const timeDiff = Math.abs(currentTime.getTime() - previousTime.getTime())
    
    console.log(`时间标注判断 - 消息${index}:`, {
      currentTime: currentTime.toISOString(),
      previousTime: previousTime.toISOString(),
      timeDiff: timeDiff,
      shouldShow: timeDiff >= 300000
    })
    
    // 如果时间差超过5分钟（300000毫秒），显示时间标注
    return timeDiff >= 300000
  }
  
  // 调试消息样式判断
  const debugMessageStyle = (message) => {
    const messageSenderId = Number(message.senderId)
    const currentUserIdNum = Number(currentUserId.value)
    const isSelf = messageSenderId === currentUserIdNum
    
    console.log('🔍 消息样式调试:', {
      content: message.content,
      senderId: message.senderId,
      messageSenderId: messageSenderId,
      currentUserId: currentUserId.value,
      currentUserIdNum: currentUserIdNum,
      isSelf: isSelf,
      senderId类型: typeof message.senderId,
      currentUserId类型: typeof currentUserId.value,
      '===比较结果': messageSenderId === currentUserIdNum,
      '==比较结果': messageSenderId == currentUserIdNum,
      'userStore.profile?.uid': userStore.profile?.uid,
      'userStore.profile': userStore.profile
    })
    
    if (isSelf) {
      console.log('🔍 应该应用右对齐样式 (自己的消息)')
    } else {
      console.log('🔍 应该应用左对齐样式 (对方的消息)')
    }
  }
  
  // 返回上一页
  const goBack = () => {
    uni.navigateBack()
  }
  
  // 清空聊天记录
  const clearChat = () => {
    uni.showModal({
      title: '确认清空',
      content: '确定要清空聊天记录吗？',
      success: (res) => {
        if (res.confirm) {
          // 实现清空聊天记录逻辑
          console.log('清空聊天记录')
          showMoreOptions.value = false
        }
      }
    })
  }
  
  // 拉黑用户
  const blockUser = () => {
    uni.showModal({
      title: '确认拉黑',
      content: `确定要拉黑用户 ${chatUserName.value} 吗？`,
      success: (res) => {
        if (res.confirm) {
          // 实现拉黑用户逻辑
          console.log('拉黑用户')
          showMoreOptions.value = false
        }
      }
    })
  }
  
  // 跳转到用户个人主页
  const goToUserProfile = (userId) => {
    if (!userId) {
      console.warn('用户ID为空，无法跳转到个人主页')
      return
    }
    
    console.log('跳转到用户个人主页，用户ID:', userId)
    
    // 先存储要查看的用户ID，然后跳转到个人页面
    uni.setStorageSync('routeUid', userId);
    uni.setStorageSync('viewOtherUser', 'true'); // 添加标记表示要查看其他用户
    
    // 跳转到个人主页，使用switchTab因为profile是tabbar页面
    uni.switchTab({
      url: '/pages/profile/index',
      success: () => {
        console.log('成功跳转到个人主页')
      },
      fail: (error) => {
        console.error('跳转到个人主页失败:', error)
        uni.showToast({
          title: '跳转失败',
          icon: 'none'
        })
      }
    })
  }

  // 错误处理
  const handleHeaderAvatarError = () => {
    console.log('头部头像加载失败')
  }
  
  const handleMessageAvatarError = () => {
    console.log('消息头像加载失败')
  }
  
  const handleCurrentUserAvatarError = () => {
    console.log('当前用户头像加载失败')
  }
</script>

<style scoped>
  .chat-detail-page {
    display: flex;
    flex-direction: column;
    height: 100vh;
  background: #f5f5f5;
}

.header-bar {
    display: flex;
    align-items: center;
    padding: 12px 16px;
  background: #4A90E2;
  color: white;
  }
  
  .header-left, .header-right { display: none; }
  
  .header-center {
    flex: 1;
  display: flex;
  align-items: center;
    justify-content: center;
  }
  
  /* 去除头像显示 */
  .header-avatar { display: none; }
  
  .header-info {
  display: flex;
    flex-direction: column;
  align-items: center;
  }
  
  .header-name {
    font-size: 16px;
    font-weight: bold;
    color: white;
  }
  
  .header-status {
    font-size: 12px;
    color: rgba(255, 255, 255, 0.8);
  }
  
  .header-status.online {
    color: #4CAF50;
  }
  
  .back-btn, .more-btn { display: none; }
  .back-btn::after, .more-btn::after { border: 0 none !important; display: none; }
  
  .chat-messages {
    flex: 1;
  padding: 16px;
    overflow-y: auto;
    scroll-behavior: smooth;
    transition: scroll-behavior 0.3s ease;
    width: 100%;
    max-width: 100%;
    box-sizing: border-box;
}

.loading-spinner {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
}

.spinner {
  width: 32px;
  height: 32px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #4A90E2;
  border-radius: 50%;
  animation: spin 1s linear infinite;
    margin-bottom: 12px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

  .messages-container {
  display: flex;
  flex-direction: column;
    gap: 12px;
    width: 100%;
    max-width: 100%;
    overflow: hidden;
  }
  
  .message-item {
    display: flex;
    align-items: flex-start;
    gap: 8px;
    margin-bottom: 12px;
    width: 100%;
    max-width: 100%;
    overflow: hidden;
    flex-wrap: nowrap; /* 防止超长内容把头像挤到下一行 */
  }
  
  /* 对方消息 - 左对齐 */
  .message-other {
    flex-direction: row;
    justify-content: flex-start;
    align-items: flex-start;
    flex-wrap: nowrap;
  }
  
  .message-other .message-avatar {
    margin-top: 4px;
    margin-right: 8px;
    margin-left: 0;
  }
  
  .message-other .message-content {
    align-items: flex-start;
  }
  
  /* 自己的消息 - 右对齐 */
  .message-self {
    flex-direction: row-reverse;
    justify-content: flex-end;
    align-items: flex-start;
    flex-wrap: nowrap;
  }
  
  .message-self .message-avatar {
    margin-top: 4px;
    margin-left: 8px;
    margin-right: 0;
  }
  
  .message-self .message-content {
    align-items: flex-end;
  }
  
  .message-avatar {
    width: 36px;
    height: 36px;
    flex-shrink: 0;
    margin-top: 4px;
    display: inline-block;
    cursor: pointer;
    transition: transform 0.2s ease;
  }
  
  .message-avatar:hover {
    transform: scale(1.05);
  }
  
  .message-avatar:active {
    transform: scale(0.95);
  }
  
  .avatar {
    width: 100%;
    height: 100%;
    border-radius: 18px;
    object-fit: cover;
    border: 2px solid rgba(255, 255, 255, 0.2);
  }
  
  .message-content {
    max-width: calc(100% - 60px); /* 预留头像与间距宽度，避免换行 */
    min-width: 60px;
    word-wrap: break-word;
    word-break: break-word;
    overflow-wrap: break-word;
    flex: 0 1 calc(100% - 60px); /* 不扩张到把头像挤换行 */
  display: flex;
  flex-direction: column;
  }
  
  .message-bubble {
    background: white;
    padding: 12px 16px;
    border-radius: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    position: relative;
    word-wrap: break-word;
    word-break: break-word;
    overflow-wrap: break-word;
    white-space: pre-wrap;
    max-width: 100%;
    width: fit-content;
    min-width: 60px;
    max-width: calc(100% - 60px);
  }
  
  .message-bubble.bubble-self {
    background: linear-gradient(135deg, #4A90E2, #357ABD);
    color: white;
    box-shadow: 0 2px 8px rgba(74, 144, 226, 0.3);
  }
  
  /* 处理超长数字和连续字符 */
  .message-text {
    font-size: 15px;
    line-height: 1.5;
    display: block;
    margin-bottom: 6px;
    font-weight: 400;
    word-wrap: break-word;
    word-break: break-all;
    overflow-wrap: anywhere;
    white-space: pre-wrap;
    max-width: 100%;
    hyphens: auto;
    -webkit-hyphens: auto;
    -ms-hyphens: auto;
  }
  
  .message-meta {
  display: flex;
  align-items: center;
    justify-content: space-between;
  gap: 8px;
  }
  
  .message-time {
    font-size: 11px;
    opacity: 0.8;
    font-weight: 400;
  }
  
  .message-status {
    font-size: 10px;
    opacity: 0.9;
    font-weight: 500;
  }
  
  .input-section {
    padding: 16px;
  background: white;
    border-top: 1px solid #f0f0f0;
    backdrop-filter: blur(10px);
  }
  
  .input-container {
    display: flex;
    gap: 12px;
    align-items: center;
  }
  
  .message-input {
    flex: 1;
    height: 44px;
    padding: 0 18px;
    border: 1px solid #e8e8e8;
    border-radius: 22px;
    font-size: 15px;
    background: #f8f9fa;
  transition: all 0.3s ease;
}

  .message-input:focus {
    border-color: #4A90E2;
    background: white;
    box-shadow: 0 0 0 3px rgba(74, 144, 226, 0.1);
  }
  
  .send-btn {
    padding: 0 24px;
    height: 44px;
  background: linear-gradient(135deg, #4A90E2, #357ABD);
  color: white;
    border: none;
    border-radius: 22px;
    font-size: 15px;
    font-weight: 500;
    box-shadow: 0 2px 8px rgba(74, 144, 226, 0.3);
    transition: all 0.3s ease;
  }
  
  .send-btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(74, 144, 226, 0.4);
  }
  
  .send-btn:disabled {
    background: #ccc;
    box-shadow: none;
    transform: none;
  }
  
  .modal-mask {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
  }
  
  .modal-content {
  background: white;
  border-radius: 12px;
    width: 80%;
    max-width: 300px;
}

  .modal-header {
  display: flex;
  align-items: center;
    justify-content: space-between;
    padding: 16px;
    border-bottom: 1px solid #e0e0e0;
  }
  
  .modal-title {
    font-size: 16px;
    font-weight: bold;
  color: #333;
}

  .modal-close {
    background: none;
  border: none;
    font-size: 20px;
    color: #999;
    padding: 0;
    width: 24px;
    height: 24px;
  }
  
  .modal-body {
    padding: 16px;
  }
  
  .option-btn {
    width: 100%;
  padding: 12px;
    background: none;
    border: 1px solid #ddd;
  border-radius: 8px;
    font-size: 14px;
    color: #333;
    margin-bottom: 8px;
  }
  
  .option-btn:last-child {
    margin-bottom: 0;
  }
  
  .load-more-container {
    display: flex;
    justify-content: center;
    padding: 16px;
  }
  
  .load-more-btn {
    background: #f0f0f0;
    color: #666;
    border: 1px solid #ddd;
    padding: 8px 16px;
    border-radius: 20px;
    font-size: 12px;
  }
  
  .loading-more {
  display: flex;
  flex-direction: column;
    align-items: center;
    padding: 16px;
    gap: 8px;
  }
  
  .loading-more .spinner {
    width: 20px;
    height: 20px;
    border: 2px solid #f3f3f3;
    border-top: 2px solid #4A90E2;
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }
  
  .loading-more text {
  font-size: 12px;
    color: #999;
  }
  
  .time-label {
    display: flex;
    justify-content: center;
    margin: 20px 0 16px 0;
  }
  
  .time-text {
    background: rgba(0, 0, 0, 0.08);
    color: #999;
    padding: 6px 14px;
    border-radius: 16px;
  font-size: 12px;
    font-weight: 500;
    text-align: center;
    backdrop-filter: blur(10px);
  }
  
  .scroll-to-bottom-btn {
    position: fixed;
    bottom: 80px;
    right: 20px;
    background: linear-gradient(135deg, #4A90E2, #357ABD);
    color: white;
    padding: 10px 16px;
    border-radius: 24px;
  display: flex;
    align-items: center;
    gap: 6px;
    box-shadow: 0 4px 16px rgba(74, 144, 226, 0.4);
    z-index: 100;
    cursor: pointer;
    transition: all 0.3s ease;
    backdrop-filter: blur(10px);
  }
  
  .scroll-to-bottom-btn:hover {
    background: linear-gradient(135deg, #357ABD, #2c5aa0);
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(74, 144, 226, 0.5);
  }
  
  .scroll-btn-icon {
    font-size: 16px;
    font-weight: bold;
  }
  
  .scroll-btn-text {
    font-size: 13px;
  font-weight: 600;
}
</style>
  